<template>
  <n-card :title="title" size="small" class="receipt-container">
    <div id="receiptContent" ref="receiptContentRef" class="receipt-preview">
      <!-- 小票抬头 -->
      <div class="receipt-header">
        <h2 class="text-center">
          {{ storeInfo.name }}
        </h2>
        <p class="text-center">
          {{ storeInfo.address }}
        </p>
        <p class="text-center">
          {{ storeInfo.phone }}
        </p>
        <p class="text-center">
          订单号: {{ orderInfo.id }}
        </p>
        <p class="text-center">
          日期: {{ formattedDate }}
        </p>
      </div>

      <!-- 商品列表 -->
      <n-divider />

      <div class="receipt-items">
        <div class="item-row header-row">
          <span class="item-name">商品名称</span>
          <span class="item-price">单价</span>
          <span class="item-quantity">数量</span>
          <span class="item-total">小计</span>
        </div>

        <div v-for="(item, index) in items" :key="index" class="item-row">
          <span class="item-name">{{ item.name }}</span>
          <span class="item-price">{{ formatCurrency(item.price) }}</span>
          <span class="item-quantity">{{ item.quantity }}</span>
          <span class="item-total">{{ formatCurrency(item.price * item.quantity) }}</span>
        </div>
      </div>

      <n-divider />

      <!-- 总计 -->
      <div class="receipt-total">
        <div class="total-row">
          <span class="flex-2-left">商品总数:</span>
          <span class="flex-2-right">{{ totalQuantity }}件</span>
        </div>

        <div class="total-row">
          <span class="flex-2-left">合计:</span>
          <span class="flex-2-right">{{ formatCurrency(totalAmount) }}</span>
        </div>

        <div v-if="orderInfo.discount > 0" class="total-row">
          <span class="flex-2-left">优惠:</span>
          <span class="flex-2-right">-{{ formatCurrency(orderInfo.discount) }}</span>
        </div>

        <div class="total-row">
          <span class="flex-2-left">应收:</span>
          <span class="flex-2-right">{{ formatCurrency(netAmount) }}</span>
        </div>
      </div>

      <!-- 支付信息 -->
      <n-divider />

      <div class="receipt-payment">
        <div class="payment-row">
          <span class="flex-2-left">支付方式:</span>
          <span class="flex-2-right">{{ orderInfo.paymentMethod }}</span>
        </div>

        <div class="payment-row">
          <span class="flex-2-left">实收:</span>
          <span class="flex-2-right">{{ formatCurrency(orderInfo.amountReceived) }}</span>
        </div>

        <div class="payment-row">
          <span class="flex-2-left">找零:</span>
          <span class="flex-2-right">{{ formatCurrency(changeAmount) }}</span>
        </div>
      </div>

      <!-- 页脚 -->
      <n-divider />

      <div class="receipt-footer">
        <p class="text-center">
          {{ footerMessage }}
        </p>
        <p class="text-center">
          {{ storeInfo.businessHours }}
        </p>
        <div v-if="showQRCode" class="qrcode-container">
          <img v-if="qrCodeUrl" :src="qrCodeUrl" alt="支付二维码" class="qrcode">
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <template #footer>
      <n-space justify="end">
        <n-button type="primary" :loading="printing" @click="printReceipt">
          <template #icon>
            <!-- <n-icon><PrinterIcon /></n-icon> -->
          </template>
          打印小票
        </n-button>
        <n-button secondary :loading="exporting" @click="exportAsImage">
          <template #icon>
            <!-- <n-icon><ImageIcon /></n-icon> -->
          </template>
          导出为图片
        </n-button>
      </n-space>
    </template>
  </n-card>
</template>

<script setup>
import html2canvas from 'html2canvas'
import { useMessage } from 'naive-ui'
import printJS from 'print-js'
import { computed, ref, watch } from 'vue'
// import { Printer as PrinterIcon, Image as ImageIcon } from '@vicons/fa'

const props = defineProps({
  title: {
    type: String,
    default: '超市小票打印',
  },
  storeInfo: {
    type: Object,
    default: () => ({
      name: '便民超市',
      address: 'XX市XX区XX路123号',
      phone: '联系电话: 400-123-4567',
      businessHours: '营业时间: 8:00-22:00',
    }),
  },
  orderInfo: {
    type: Object,
    default: () => ({
      id: `ORD${Date.now().toString().slice(-6)}`,
      date: new Date(),
      paymentMethod: '现金支付',
      amountReceived: 200,
      discount: 5.0,
    }),
  },
  items: {
    type: Array,
    default: () => [
      { id: 1, name: '可口可乐 500ml', price: 3.5, quantity: 2 },
      { id: 4, name: '蒙牛纯牛奶 250ml', price: 3.0, quantity: 2 },
    ],
  },
  footerMessage: {
    type: String,
    default: '谢谢惠顾，欢迎再次光临！',
  },
  showQRCode: {
    type: Boolean,
    default: false,
  },
  qrCodeUrl: {
    type: String,
    default: '',
  },
  printOptions: {
    type: Object,
    default: () => ({
      printable: 'receiptContent',
      type: 'html',
      targetStyles: '*',
      scanStyles: true,
    }),
  },
})

//  const emit = defineEmits([])

const message = useMessage()
const receiptContentRef = ref(null)
const printing = ref(false)
const exporting = ref(false)

// 计算属性
const totalQuantity = computed(() => {
  return props.items.reduce((sum, item) => sum + item.quantity, 0)
})

const totalAmount = computed(() => {
  return props.items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
})

const netAmount = computed(() => {
  return totalAmount.value - (props.orderInfo.discount || 0)
})

const changeAmount = computed(() => {
  return (props.orderInfo.amountReceived || 0) - netAmount.value
})

const formattedDate = computed(() => {
  return props.orderInfo.date?.toLocaleString() || new Date().toLocaleString()
})

// 方法
function formatCurrency(value) {
  return `¥${Number(value).toFixed(1)}`
}

function printReceipt() {
  // --------------------------printJS打印-----------------------------------
  printing.value = true
  // emit('printStart')

  const printOptions = {
    ...props.printOptions,
    printable: 'receiptContent',
  }

  printJS(printOptions)

  printJS.onPrintDialogClose = () => {
    printing.value = false
    // emit('printEnd')
    message.success('打印完成')
  }
  // -----------------------------------原始打印-----------------------------------
  // message.success('正在准备打印...')

  // // 在实际应用中，这里可以使用专门的打印库如Print.js
  // // 这里使用浏览器原生打印功能
  // const printContent = receiptContentRef.value.innerHTML
  // const originalContent = document.body.innerHTML

  // document.body.innerHTML = `
  //   <div style="width: 80mm; margin: 0 auto; font-family: 'Courier New', monospace;">
  //     ${printContent}
  //   </div>
  // `

  // window.print()
  // document.body.innerHTML = originalContent
  // message.success('打印完成')
}

async function exportAsImage() {
  exporting.value = true
  // emit('exportStart')

  try {
    const canvas = await html2canvas(receiptContentRef.value, {
      scale: 2,
      backgroundColor: null,
      logging: false,
      useCORS: true,
    })

    const link = document.createElement('a')
    link.download = `小票_${props.orderInfo.id}.png`
    link.href = canvas.toDataURL('image/png')
    link.click()

    message.success('导出图片成功')
  }
  catch (error) {
    message.error(`导出图片失败: ${error.message}`)
  }
  finally {
    exporting.value = false
    // emit('exportEnd')
  }
}

// 监听props变化
watch(() => props.items, (newItems) => {
  if (!newItems || newItems.length === 0) {
    message.warning('商品列表为空')
  }
}, { immediate: true })
</script>

<style scoped>
.receipt-container {
  max-width: 600px;
  margin: 0 auto;
}

.receipt-preview {
  width: 100%;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.4;
  color: #000;
  background-color: white;
  padding: 16px;
}

.text-center {
  text-align: center;
  margin: 4px 0;
}

.receipt-items {
  width: 100%;
}

.item-row {
  display: flex;
  justify-content: space-between;
  margin: 4px 0;
}

.header-row {
  font-weight: bold;
  border-bottom: 1px dashed #ccc;
  padding-bottom: 4px;
}

.item-name {
  flex: 3;
}

.item-price,
.item-quantity,
.item-total {
  flex: 1.5;
  text-align: right;
  padding-left: 8px;
}
.flex-2-right {
  flex: 1;
  text-align: right;
  padding-left: 8px;
}
.flex-2-left {
  flex: 1;
  text-align: left;
  padding-left: 8px;
}
.receipt-total,
.receipt-payment {
  margin-top: 8px;
}

.total-row,
.payment-row {
  display: flex;
  justify-content: space-between;
  margin: 4px 0;
}

.receipt-footer {
  margin-top: 16px;
  font-size: 12px;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.qrcode {
  width: 100px;
  height: 100px;
  border: 1px solid #eee;
}

/* 响应式调整 */
@media (max-width: 640px) {
  .receipt-container {
    width: 100%;
    max-width: 100%;
  }

  .receipt-preview {
    padding: 10px;
    font-size: 12px;
  }
}
</style>
